package com.andrew.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.andrew.entity.Customer;
import com.andrew.entity.PageBean;
import com.andrew.service.BookService;
import com.andrew.service.impl.BookServiceImpl;
import com.google.gson.Gson;

/**
 * Servlet implementation class SearchBooksByPageServlet
 */
@WebServlet("/SearchBooksByPageServlet")
public class GetBooksByPageServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//设置编码
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		//设置当前页数
		HttpSession session = request.getSession();
		Object currentPageObj=session.getAttribute("currentPage");
		
		//当前会话第一次访问
		if(currentPageObj==null) {
			session.setAttribute("currentPage", 1);
		}
		
		
		 
		//获取当前页数
		int currentPage=(int)(request.getSession().getAttribute("currentPage"));
		//获取搜索条件,是空值的话为"",不是空值的话为查询条件
		String queryTerm="";
		Object queryTermObj=request.getSession().getAttribute("queryTerm");
		if(queryTermObj!=null) {
			queryTerm=(String)queryTermObj;
		}
		
		//获取当前页的信息
		BookService bookService =new BookServiceImpl();
		PageBean pageBean=null;
		try {
			pageBean = bookService.getBooksByPage(queryTerm,currentPage);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//装换为json
		Gson gson =new Gson();
		String json = gson.toJson(pageBean).toString();
		response.getWriter().write(json);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
